package com.haifeng.sbtx.auth.exception;

import com.alibaba.fastjson.JSONObject;
import com.haifeng.sbtx.common.base.ErrorCode;
import com.haifeng.sbtx.common.base.JsonSerializer;
import com.haifeng.sbtx.common.base.Rest;
import com.haifeng.sbtx.common.util.MessageUtil;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 *  认证失败处理器
 * </p>
 *
 * @author: Haifeng
 * @date: 2019-12-15
 */
@Component("authExceptionEntryPoint")
@AllArgsConstructor
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    private final MessageUtil messageUtil;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws ServletException {
        response.setContentType("application/json;charset=UTF-8");
        Rest error;
        if(authException.getCause() instanceof InvalidTokenException) {
            error = Rest.error(HttpStatus.UNAUTHORIZED.value(), messageUtil.getMessage(ErrorCode.INVALID_TOKEN));
        }else{
            error = Rest.error(HttpStatus.UNAUTHORIZED.value(), messageUtil.getMessage(ErrorCode.NEED_AUTH));
        }
        try {
            response.getWriter().write(JSONObject.toJSONString(error, JsonSerializer.serializerFeatures));
        } catch (IOException e) {
            throw new ServletException(e.getCause());
        }
    }
}
